<template>
  <t-modal
    title="上传"
    width="900px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="onSubmit()"
    wrapClassName="add-modal-container"
    v-bind="footer"
    forceRender
    :confirmLoading="submitLoading"
  >
    <div class="curve-modal-body">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item label="文件夹名称">
          <a-input v-model="treeItem.nodeName" disabled />
        </a-form-model-item>
        <a-form-model-item
          label="文件"
          prop="files"
          :rules="{
            required: true,
            message: '请选择文件',
          }"
        >
          <bjUploadFile
            :count="30"
            v-model="form.files"
            @preview="viewFile($event)"
            @download="downloadFile($event)"
            @change="handleUpLoadFile($event)"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import { mapGetters } from "vuex";
import { getToken, downloadDfs } from "@/utils/TopVUI";
//附件上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
export default {
  components: {
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    treeItem: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      footer: {},
      submitLoading: false,
      form: {
        //文件名称
        name: "",
        //文件
        files: [],
      },
      rules: {},
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
        }
      },
      immediate: true,
    },
  },

  methods: {
    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { form, treeItem } = this;
          const fileList = form.files.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );
          let formJson = {
            //目录id
            treeUuid: treeItem.uuid,
            //文件名称
            name: form.name,
            //文件
            fileAddress: JSON.stringify(fileList),
          };
          this.submitLoading = true;
          axios
            .post(`/probusiness/projectInitiationFile/save`, formJson, {
              headers: {
                "Content-Type": "application/json;charset=UTF-8",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("上传成功", 1.5);
                this.$emit("onRefresh");
                this.closeModal();
              } else {
                this.$message.error(res?.message ?? "上传失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.submitLoading = false;
            });
        }
      });
    },

    //上传附件
    handleUpLoadFile({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["files"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form["files"][index], "dfsFileUuid", res.dfsFileUuid);
          this.$set(this.form["files"][index], "url", res.url);
          this.form.name = file.name;
        })
        .catch((_) => {
          this.form.name = "";
          this.$set(this.form["files"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["files"][index], "loading", false);
        });
    },

    //下载
    downloadFile(row) {
      let { url } = row;
      downloadDfs(url);
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //重置表单
    resetForm() {
      this.form = {
        //文件名称
        name: "",
        //文件
        files: [],
      };
      this.$refs.ruleForm.resetFields();
    },

    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
    .curve-modal-body {
      box-sizing: border-box;
      padding: 14px 70px 14px 40px;
      max-height: 700px;
      overflow: auto;
      .ant-form-item {
        display: flex;
        .ant-form-item-label {
          flex-shrink: 0;
          width: 140px;
          label {
            color: #333333;
          }
        }
        .ant-form-item-control-wrapper {
          flex: 1;
          overflow: hidden;
        }
      }
      .bj-upload-file {
        .choosed-file-warp {
          width: 100%;
        }
      }
    }
  }
}
</style>
